<template>
	<view>
		<view class="comment-container " :class="{hide:!hide}">
			<view class="header">
				<view v-if=" feed.feed_comment_count " class="total">
					{{ feed.feed_comment_count }}条评论
				</view>
				<view v-else class="total">评论</view>
				<view class="close" @click="onClose">×</view>
			</view>

			<scroll-view scroll-y class="scroll-view" @scrolltolower="onLoadmore">
				<view v-if=" !feed.feed_comment_count " class="no-content">还没有人评论 😢</view>
				<view v-else class="comments">
					<view class="comment-item hairline-bottom" v-for="item in comments " :key="commentid" :data-comment=" item "
					 @longpress="onReport" @click="onClick">
						<avatar :user=" item.user "></avatar>
						<view class="info-wrap">
							<!-- TODO: 认证信息 (need 缓存中间件) -->
							<view class="username">{{ item.user.name }}</view>
							<view class="content">
								<block v-if=" item.reply_user ">回复<text class="reply-name">{{ item.reply.name }}:</text></block>{{ item.body }}
							</view>
						</view>
						<view class="time">{{ fromNow(item.created_at) }}</view>
					</view>
				</view>
			</scroll-view>

			<view class="comment-input" :style="{top: -keyboardOffsetTop +'px'}">
				<input class="input-placeholder" :placeholder=" inputPlaceholder || '发表我的评论...' " :focus=" inputFocus "
				 conform-type="send" :value=" inputValue " cursor-spacing="12" :adjust-position=" false " @input="onInputComment"
				 @focus="onInputFocus" @blur="onInputBlur" @confirm="onConfirmComment" confirm-type="send" />
				<image class="like-icon" :src="feed.has_liked ? '../../static/sns/ico_momentslist_zan_on@2x.png' : '../../static/sns/ico_momentslist_zan@2x.png'"
				 mode="aspectFit" @click="onLikeFeed"></image>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		$storage
	} from "@/utils";
	export default {
		data() {
			return {
				loading: true,
				show: false,
				feedId: 0,
				feed: {},
				comments: [],
				noMore: false,
				inputValue: '',
				inputFocus: false,
				inputPlaceholder: '',
				replyUser: null,
				keyboardOffsetTop: 0,
				index: '',
				hide: false,
			};
		},
		methods: {
			getDate(d) {
				return d ? new Date(d) : new Date()
			},
			/** 获取目标时间到当前时间的时间差 */
			fromNow(time) {
				let date
				// prettier-ignore
				// eslint-disable-next-line
				if (typeof time === 'string' && /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(time)) {
					time = time.replace(/-/g, '/')
					date = this.getDate(time)
					const offset = getDate().getTimezoneOffset() * 60 * 1000
					date = this.getDate(+date - offset)
				} else {
					date = this.getDate(time)
				}
				const now = Date.now()
				const diff = (now - +date) / 1000
				let relative = diff
			
				if (relative < 60) {
					return '1分钟内'
				}
				relative = Math.floor(relative / 60)
				if (relative < 60) {
					return relative + '分钟前'
				}
				relative = Math.floor(relative / 60)
				if (relative < 24) {
					return relative + '小时前'
				}
			
				const timeString = date.toTimeString().substring(0, 5)
				relative = Math.floor(relative / 24)
				if (this.isYesterday(date)) {
					return '昨天 ' + timeString
				}
				if (relative < 9) {
					return relative + '天前'
				}
				return date.getMonth() + 1 + '-' + date.getDate()
			},
			/** 检测目标日前是否是今天 */
			isYesterday(target) {
				// prettier-ignore
				// eslint-disable-next-line
				if (typeof target === 'string' && /\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(target)) {
					target = target.replace(/-/g, '/')
				}
				const date = this.getDate()
				const today = +this.getDate(date.getFullYear(), date.getMonth(), date.getDate()) // 今日凌晨
				const yesterday = +this.getDate(today - 1000 * 24 * 3600) // 昨日凌晨
				const now = +this.getDate(target)
				return now < today && now > yesterday
			},
			async open(feedId) {
				this.show = true;
				this.feedId = feedId;
				this.hide = true;
				const res = await this.$u.api.getFeedComments({id:feedId}, {
					limit: 15
				})
				const noMore = res.comments.length < 15

				this.comments = res.comments;
				this.feed = res.feed;
				this.loading = false;
				this.noMore = noMore;
				this.inputValue = '';
				this.inputFocus = false;
				this.inputPlaceholder = '';
				this.replyUser = null
			},
			async onLoadmore() {
				if (this.noMore) return
				wx.showLoading({
					title: '加载中'
				})
				const after = this.getLastField(this.comments)
				const res = await this.$u.api.getFeedComments({id:this.feedId}, {
					after,
					limit: 15
				})
				const noMore = res.comments.length < 15
				this.comments = [...this.comments, ...res.comments];
				this.noMore = noMore
				wx.hideLoading()
			},
			getLastField(list, field = 'id') {
				const last = list[list.length - 1] || {}
				if (typeof last === 'object') {
					return last[field]
				} else {
					return last
				}
			},
			onClose() {
				this.hide = false;
				this.pinneds = [];
				this.show = false;
				this.comments = [];
				this.feedId = 0;
			},
			async onInputFocus(event) {
				// await this.$u.api.checkLogin()
				const {
					height
				} = event.detail
				this.keyboardOffsetTop = height
			},
			onInputBlur() {
				this.keyboardOffsetTop = 0;
				this.inputFocus = false
			},
			onInputComment({
				detail = {}
			}, targetValue) {
				const value = detail.value
				return {
					value: targetValue || value,
					pos: detail.cursor || 0,
				}
			},
			async onConfirmComment({
				detail
			}) {
				// 内容安全审核
				const checkRes = await wx.serviceMarket.invokeService({
					service: 'wxee446d7507c68b11',
					api: 'msgSecCheck',
					data: {
					  "Action": 'TextApproval',
					  "Text": detail.value,
					}
				});
				if(checkRes.data.Response.EvilTokens.length >0 ){
					uni.hideToast();
					uni.showModal({
					    title: '发布失败',
					    content: '您的评论涉及敏感内容：“'+checkRes.data.Response.EvilTokens[0].EvilKeywords[0]+"”",
					    success: res => {
					       
					    }
					});
					this.inputFocus = false
					return;
				}
				
				const payload = {
					body: detail.value
				}
				if (this.replyUser) payload.reply_user = this.replyUser.id
				console.log(payload)
				const res = await this.$u.api.sendComment({
					id: this.feedId,
					type: 'feeds',
					body: payload.body
				})
				const {
					comment,
					amount
				} = res
				if (amount) {
					uni.$emit('showMessage', {
						message: '评论成功',
						amount: amount,
					})
				} else {
					wx.showToast({
						title: '评论成功',
						icon: 'success',
						duration: 2000,
					})
				}
				const comments = [comment, ...this.comments]
				this.$set(this, 'comments', comments)
				this.$set(this.feed, 'feed_comment_count', this.feed.feed_comment_count + 1)
				this.inputFocus = false
				this.inputValue = ''
				this.replyUser = null
			},
			async onLikeFeed() {
				// $event.emit('after:onLike', +this.data.index)
				// $event.emit('dGiveUp', {
				// 	id: this.data.feed.id
				// })

				// await this.$u.api.checkLogin()
				const feed = this.feed

				if (feed.has_liked) {
					this.$u.api.unlikeFeed(feed.id)
				} else {
					this.$u.api.likeFeed(feed.id)
				}
				this.$set(this.feed, 'has_liked', !feed.has_liked)
				this.$set(this.feed, 'like_count', feed.like_count + (!feed.has_liked ? 1 : -1))
				
			},
			async onClick(event) {
				// await this.$u.api.checkLogin()
				const data = event.currentTarget.dataset
				const comment = data.comment
				if ($storage.get('user').id === comment.user_id) {
					wx.showActionSheet({
						itemList: ['删除评论'],
						success: async ({
							tapIndex
						}) => {
							if (tapIndex === 0) {
								wx.showLoading({
									title: '删除中'
								})
								await this.$u.api.deleteComment({type:'feeds',id:this.feedId,comment_id:comment.id})
								wx.hideLoading()
								const newList = this.comments.filter(
									(item) => item.id !== comment.id,
								)
								this.$set(this, 'comments', newList)
								this.$set(this.feed, 'feed_comment_count', this.feed.feed_comment_count - 1)
							}
						},
					})
				} else {
					this.inputFocus = true;
					this.replyUser = comment.user;
					this.inputPlaceholder = `回复 ${comment.user.name}: `
				}
			},
			async onReport(event) {
				const data = event.currentTarget.dataset
				// await this.$u.api.checkLogin()
				if ($storage.get('user').id === data.comment.user_id) return
				wx.navigateTo({
					url: `/feed/report?type=feed&id=${data.comment.id}`,
				})
			}
		}
	}
</script>

<style lang="scss">
	@import '../../var';
	@import '../../common';

	.back-cover {
		position: fixed;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: $zindex-cover;
		background-color: rgba(0, 0, 0, 0.2);
		transition: all ($transition-time / 2);
	}

	.hide {
		z-index: -1;
		opacity: 0;
	}

	.comment-container {
		position: fixed;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: $zindex-dialog;
		display: flex;
		flex-direction: column;
		//Instead of the line below you could use @include box-sizing($bs)
		box-sizing: border-box;
		height: 75%;
		padding: $lg 0 0;
		background-color: #fff;
		//Instead of the line below you could use @include border-radius($radius, $vertical-radius)
		border-radius: $md $md 0 0;
		//Instead of the line below you could use @include transition($transition-1, $transition-2, $transition-3, $transition-4, $transition-5, $transition-6, $transition-7, $transition-8, $transition-9, $transition-10)
		transition: opacity $transition-time, transform $transition-time;
		pointer-events: none;
		pointer-events: auto;

		&.hide {
			z-index: -1;
			transform: translateY(100%);
			opacity: 0;
		}

		.comment-input {
			position: relative;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 16rpx 30rpx;
			background-color: #f4f4f6;
			font-size: 28rpx;
			color: #afb4be;

			.input-placeholder {
				display: flex;
				flex: auto;
				align-items: center;
				min-width: 0;
				height: 70rpx;
				margin-right: $xl;
				padding-left: $md;
				color: $decor-color;
				font-size: $font-size-small;
				background-color: $bgcolor-light;
				border-radius: 110rpx;
				font-size: 28rpx;
				color: #afb4be;
			}

			.like-icon {
				flex: none;
				width: $lg * 1.5;
				height: $lg * 1.5;
			}
		}

		.scroll-view {
			flex: auto;
			min-height: 0;
			overflow-x: scroll;
			// height: calc(100% - 48rpx - 110rpx);
		}

		.header {
			display: flex;
			flex: none;
			align-items: center;
			justify-content: space-between;
			height: 48rpx;
			margin-bottom: $lg;
			padding: 20rpx 30rpx;
			line-height: $xl;

			.close {
				font-weight: 100;
				font-size: 150%;
			}
		}
	}

	.no-content {
		display: flex;
		justify-content: center;
		padding-top: 200rpx;
		color: $info-color;
	}

	.comments {
		font-size: $font-size-small;

		.comment-item {
			display: flex;
			padding: $md $xl;

			.avatar {
				flex: none;
			}

			.info-wrap {
				flex: auto;
				margin: 0 $md;

				.username {
					margin-bottom: $sm;
				}

				.content {
					color: $info-color;

					.reply-name {
						color: $text-color;
					}
				}
			}

			.time {
				flex: none;
				color: $info-color;
			}
		}
	}
</style>
